package vip.xiaonuo.megvii.facegroups.delete.impl;

import org.springframework.stereotype.Service;
import vip.xiaonuo.facedoor.modular.memberfeatures.entity.MemberFeatures;
import vip.xiaonuo.facedoor.modular.memberfeatures.service.MemberFeaturesService;
import vip.xiaonuo.megvii.facegroups.delete.FaceGroupDeleteStrategy;
import vip.xiaonuo.modular.facegroupfacetokenrela.entity.FacegroupFacetokenRela;
import vip.xiaonuo.modular.facegroupfacetokenrela.param.FacegroupFacetokenRelaParam;
import vip.xiaonuo.modular.facegroupfacetokenrela.service.FacegroupFacetokenRelaService;
import vip.xiaonuo.modular.megviifacegroup.entity.MegviiFaceGroup;
import vip.xiaonuo.modular.megviifacegroup.service.MegviiFaceGroupService;
import vip.xiaonuo.modular.megviifacegroup.service.impl.MegviiFaceGroupServiceImpl;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 保留群组，清空关联人脸，若人脸仅关联当前分组，删除人脸
 * 以分组内人脸为切入点，
 * 判断该人脸是否关联当前分组，
 * 若分组关联唯一，删除人脸
 * 否则，保留人脸
 */
@Service
public class DeleteFaceGroupSaveGroup extends DeleteFaceGroupBaseService implements FaceGroupDeleteStrategy {



    @Override
    public void delete(MegviiFaceGroup group) {
        // 所有人脸
        List<MemberFeatures> features = faceGroupService.listMemberFeatureByGroupId(group.getId());

        List<FacegroupFacetokenRela> toDeleteRelas = new ArrayList<>();
        List<MemberFeatures> toDeleteFeatures = new ArrayList<>();
        for (MemberFeatures feature : features){
            // 删除该分组下的人脸关联数据
            FacegroupFacetokenRelaParam param = new FacegroupFacetokenRelaParam();
            param.setFeaturesId(feature.getId());
            List<FacegroupFacetokenRela> relas = relaService.list(param);
            for(FacegroupFacetokenRela rela : relas){
                if(rela.getFaceGroupId()==group.getId()){
                    toDeleteRelas.add(rela);
                }
            }
            // 人脸只与当前分组关联,删除人脸
            if(relas.size()==1 && relas.get(0).getFaceGroupId()== group.getId()){
                toDeleteFeatures.add(feature);
            }
        }

        relaService.removeBatchByIds(toDeleteRelas);
        featuresService.removeBatchByIds(toDeleteFeatures);

        // 删除分组关联
        this.deleteFaceGroupOrgRelate(groupOrgRelateService,group.getId());
    }

}
